import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';

import { STORAGE_KEY_DISTRICT_INFO } from '../../constant';
import { DistrictInfo } from '../../api/common/getDistrictInfo';
import data from './data';

let lastDay = 0;
let districtInfo: DistrictInfo = data;

AsyncStorage.getItem(STORAGE_KEY_DISTRICT_INFO).then((res: any): void => {
  if (res) {
    const info = JSON.parse(res);
    ({ lastDay, districtInfo } = info);
  }
});

export const setDistrictData = (district: DistrictInfo): void => {
  lastDay = Number(moment().format('D'));
  districtInfo = district;

  AsyncStorage.setItem(
    STORAGE_KEY_DISTRICT_INFO,
    JSON.stringify({
      lastDay,
      districtInfo
    })
  );
};

export const getDistrictInfo = (): DistrictInfo => districtInfo;

export const needUpdateDistrictInfo = (): boolean => {
  const currentDay = Number(moment().format('D'));
  console.log('currentDay', currentDay);
  return currentDay !== lastDay;
};
